package cn.easybuy.web.pre;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.easybuy.entity.User;
import cn.easybuy.service.user.UserService;
import cn.easybuy.service.user.UserServiceImpl;
import cn.easybuy.utils.SecurityUtils;

public class UserLogin extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UserLogin() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		String opr = request.getParameter("opr");

		if(opr.equals("exit")){
			request.getSession().removeAttribute("LoginUser");
			request.getSession().removeAttribute("LoginUserType");
			request.getSession().removeAttribute("cart");
			response.sendRedirect("../pre/Index.jsp");
		}else if(opr.equals("login")){
			UserService userService = new UserServiceImpl();
			User user = userService.findOneUser(name,SecurityUtils.md5Hex3(pwd));
			if(user!=null){
				request.getSession().setAttribute("LoginUser", user);
				String type = "";
				int typeId = user.getType();
				if(typeId==0){
					type = "管理员"; //pageScope 页面 requestScope 请求 sessionScope 会话 ApplicationScope 全局
				}else if(typeId==1){
					type="普通用户";
				}
				request.getSession().setAttribute("LoginUserType", type);
				response.sendRedirect("../pre/Index.jsp");
			}else{
				out.print("<script>");
				out.print("alert('用户名或密码错误!');");
				out.print("window.location.href='Login.jsp';");
				out.print("</script>");
			}
		}else if(opr.equals("updatePwd")){
			String userName = request.getParameter("name");
			String newPwd =SecurityUtils.md5Hex3(request.getParameter("pwd"));
			UserService userService = new UserServiceImpl();
			if(userService.updatePwd(userName, newPwd)>0){
				out.print("<script>");
				out.print("alert('修改密码成功，请登录!');");
				out.print("window.location.href='Login.jsp';");
				out.print("</script>");
			}else{
				out.print("<script>");
				out.print("alert('修改密码失败，请联系管理员!');");
				out.print("window.location.href='Login.jsp';");
				out.print("</script>");
			}
			
		}
	}
}
